package nio.bytebuffer;

import java.nio.ByteBuffer;

public class Slice {

    public static void main(String[] args) {

        slice();
        System.out.println("*******************************************************");
        slice_arrayOffset();

    }

    private static void slice_arrayOffset() {
        byte[] byteArrayIn1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
        ByteBuffer bytebuffer1 = ByteBuffer.wrap(byteArrayIn1);
        bytebuffer1.position(5);
        ByteBuffer bytebuffer2 = bytebuffer1.slice();
        System.out.println(bytebuffer2.arrayOffset()); // 5
    }

    private static void slice() {
        byte[] byteArrayIn1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
        ByteBuffer bytebuffer1 = ByteBuffer.wrap(byteArrayIn1);
        bytebuffer1.position(5);
        ByteBuffer bytebuffer2 = bytebuffer1.slice();

        // bytebuffer1.position=5 bytebuffer1.capacity=8 bytebuffer1.limit=8
        System.out.println("bytebuffer1.position=" + bytebuffer1.position()
                + " bytebuffer1.capacity=" + bytebuffer1.capacity()
                + " bytebuffer1.limit=" + bytebuffer1.limit());
        // bytebuffer2.position=0 bytebuffer2.capacity=3 bytebuffer2.limit=3
        System.out.println("bytebuffer2.position=" + bytebuffer2.position()
                + " bytebuffer2.capacity=" + bytebuffer2.capacity()
                + " bytebuffer2.limit=" + bytebuffer2.limit());

        bytebuffer2. put( 0, (byte) 111);

        byte[] byteArray1 = bytebuffer1.array();
        byte[] byteArray2 = bytebuffer2.array();
        for (int i = 0; i < byteArray1.length; i++) {
            System.out.print(byteArray1[i] + " ");
        } // 1 2 3 4 5 111 7 8

        System.out.println();

        for (int i = 0; i < byteArray2.length; i++) {
            System.out.print(byteArray2[i] + " ");
        } // 1 2 3 4 5 111 7 8
        System.out.println();
    }

}
